package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.ElectronicMediaVo;
import com.app.vo.ElectronicVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/media")
public class ElectronicMediaController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private ElectronicService electronicService;
    @Autowired
    private ElectronicMediaService electronicMediaService;
    @Autowired
    private PersonService personService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        CategoryVo vo = new CategoryVo();

        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(62);
        vo.setMediaList(categoryModelList);//社交媒体类型
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        List<PersonModel> personList = personService.otherPersonList(idList);
        if (personList != null && personList.size() > 0) {
            vo.setPersonList(personList);
        }
        return Result.success(vo);
    }

    @GetMapping("/getElcList")//设备管理分页查询
    public Result<Object> getElcList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            Integer sortType,
            @RequestParam(required = false) String mediaNumber,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        List<Integer> personIdLIst = new ArrayList<>();
        List<PersonModel> modelList = personService.otherPersonList(idList);
        for (int i = 0; i < modelList.size(); i++) {
            personIdLIst.add(modelList.get(i).getId());
        }


        Page<ElectronicMediaModel> electronicMediaModelPage = electronicMediaService.getPageElcMediaList(page, limit, mediaNumber, personIdLIst,sortType);
        if (electronicMediaModelPage == null) {
            return Result.error(200, "暂无数据");
        }
        for (int i = 0; i < electronicMediaModelPage.getRecords().size(); i++) {  //查其他表

            PersonModel personModel = personService.selectPersonById(electronicMediaModelPage.getRecords().get(i).getPersonId());
            electronicMediaModelPage.getRecords().get(i).setPersonName(personModel.getName());//获取人员名字
            CategoryModel Model1 = categoryService.getCategoryById(electronicMediaModelPage.getRecords().get(i).getMediaType());
            electronicMediaModelPage.getRecords().get(i).setMediaTypeText(Model1.getName());
            if (electronicMediaModelPage.getRecords().get(i).getIllegal() == 1) {
                electronicMediaModelPage.getRecords().get(i).setIllegalText("是");
            } else {
                electronicMediaModelPage.getRecords().get(i).setIllegalText("否");

            }
        }
        int count = (int) electronicMediaModelPage.getTotal();
        List<ElectronicMediaModel> mediaModelList;
        mediaModelList = electronicMediaModelPage.getRecords();
        ElectronicMediaVo vo = new ElectronicMediaVo();
        vo.setCount(count);
        vo.setList(mediaModelList);
        return Result.success(vo);
    }

    @PostMapping("/insertMedia")//    新增/修改社交媒体
    public Result<Object> insertMedia(
            @RequestBody JSONObject json,
            HttpServletRequest request) {
        Integer id = Integer.valueOf(json.get("id").toString());
        Object mediaType = json.get("mediaType");
        String mediaNumber = json.get("mediaNumber").toString();
        Integer illegal = Integer.valueOf(json.get("illegal").toString());
        Integer personId = Integer.valueOf(json.get("personId").toString());
        Integer number = Integer.valueOf(json.get("number").toString());

        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (mediaType instanceof String) {
            CategoryModel model = new CategoryModel();
            String mediaTypeText = json.get("mediaType").toString();
            model.setPid(62);
            model.setName(mediaTypeText);
            model.setStatus(1);
            model.setSort(0);
            model.setCreateTime(CommonHelp.getNowTimestamp());
            categoryService.insert(model);
            mediaType = model.getId();
        } else {
            mediaType = Integer.valueOf(json.get("mediaType").toString());
        }
        ElectronicMediaModel mediaModel = new ElectronicMediaModel();
        mediaModel.setMediaType((Integer) mediaType);
        mediaModel.setMediaNumber(mediaNumber);
        mediaModel.setIllegal(illegal);
        mediaModel.setPersonId(personId);
        mediaModel.setNumber(number);
        try {
            if (id > 0) {
                mediaModel.setId(id);
                mediaModel.setUpdateTime(CommonHelp.getNowTimestamp());
                electronicMediaService.update(mediaModel);
            } else {
                mediaModel.setCreateTime(CommonHelp.getNowTimestamp());
                electronicMediaService.insert(mediaModel);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除社交媒体账号
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        ElectronicMediaModel roleModel = electronicMediaService.getElcMediaById(id);
        if (roleModel == null) {
            return Result.error(500, "该媒体账号不存在");
        } else {
            electronicMediaService.delete(id);
            return Result.success(null);
        }
    }

    //批量删除社交媒体账号
    @DeleteMapping("/deleteMediaBatchByIds")
    public Result<Object> deleteMediaBatchByIds(@RequestParam("ids") String ids, HttpServletRequest request){
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return  electronicMediaService.deleteMediaBatchByIds(ids);
    }

    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }
}
